package com.xyzk.diagnose.activity;

import java.io.IOException;
import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.ini4j.Profile.Section;
import org.json.JSONException;
import org.json.JSONObject;

import com.xyzk.diagnose.R;
import com.xyzk.diagnose.activity.adapter.MainAdapter;
import com.xyzk.diagnose.activity.bluetooth.BluetoothActivity;
import com.xyzk.diagnose.activity.bluetooth.BluetoothService;
import com.xyzk.diagnose.activity.other.ProblemActivity;
import com.xyzk.diagnose.activity.other.SettingActivity;
import com.xyzk.diagnose.activity.other.UpdateApp;
import com.xyzk.diagnose.entity.Cartype;
import com.xyzk.diagnose.httputils.HttpRequest;
import com.xyzk.diagnose.servies.UpdateAppService;
import com.xyzk.diagnose.tools.Common;
import com.xyzk.diagnose.tools.CommonXml;
import com.xyzk.diagnose.tools.Commonfunc;
import com.xyzk.diagnose.tools.FileReader;
import com.xyzk.diagnose.tools.Security;
import com.xyzk.diagnose.view.CToast;
import com.xyzk.diagnose.view.dialog.InputDialog;
import com.xyzk.diagnose.view.dialog.LoginDialog;
import com.xyzk.diagnose.view.dialog.ProgressDialog;
import com.xyzk.diagnose.view.dialog.SelectDialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity{
	private BluetoothService mBlueService = BluetoothService.getInstance();
	private Cartype cartype = Cartype.getInstance();
	private ProgressDialog progressdialog;
	private long historyTime;//记录时间
	private int mSize;
	private BluetoothService bluetooth = BluetoothService.getInstance();
	Context context = MainActivity.this;

	private Boolean status = true;

	/**
	 *处理蓝牙连接状态
	 */
	@SuppressLint("HandlerLeak")
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case Common.BLUE_RECEIVE_CONNECT:
					progressdialog.dismiss();
					if(mBlueService.isConnected()){
						CToast.show("连接成功!");
						startActivity(new Intent(MainActivity.this, DiagnoseActivity.class));
					}else{
						CToast.show("连接失败!");
						startActivityForResult(new Intent(MainActivity.this, BluetoothActivity.class), Common.SHOW_ACTIVITY_RESULT);
					}
					break;
				case Common.DIALOG_SHOW_TEXT:
					if(msg.arg1 == 100) //progress show text
					{
						progressdialog.setMessage((String)msg.obj);
					}
					else
						CToast.show((String)msg.obj);
					break;
				case Common.DIALOG_SHOW_PROGRESS:
					progressdialog.dismiss();
					if(msg.arg1 == 1) //ok
					{
						startDiagnose(cartype.car);
					}
					else
					{
						CToast.show((String)msg.obj);
						inputConfig();
					}
					break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initViews();
		registerRecevie();
		//todo 启动查询软件版本更新
		//启动软件更新查询服务
//		Intent it=new Intent(this, UpdateAppService.class);
//		startService(it);
		test();
	}

	@Override
	protected void onResume() {
//下载更新
		//判断是否要弹出下载更新的框
		Boolean dialog_isok = Common.dialog_isok;
		SharedPreferences sharedPreferences=getSharedPreferences("Eol_KF",MODE_PRIVATE);//拿到 sharedPreferences 的引用 MODE_PRIVATE表示只能被本应用读写，不能被其他应用读写
		Boolean softStatus = sharedPreferences.getBoolean("softStatus",false);//当key不存在时，默认返回defValue的值
		String softTime = sharedPreferences.getString("softTime","");
//		System.out.println("-------"+softTime);
		Boolean version_isok = false;
		String appVersion = sharedPreferences.getString("CheryVersion","1");
		String Version = getVersionName();
		float newVersion = Float.parseFloat(appVersion.replace("V","").replace(".",""));
		float oldVersion = Float.parseFloat(Version.replace("V","").replace(".",""));
		if (newVersion>oldVersion) {
			version_isok = true;
		}else {
			version_isok = false;
		}

		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
		String datetime = tempDate.format(new java.util.Date());
		if (softStatus&&datetime.equals(softTime)){
			//todo
//			status = false;
		}else {
			status = true;
		}
		if (version_isok&&status&&dialog_isok) {
			final UpdateApp dialog = new UpdateApp(MainActivity.this);
			dialog.show();
			Common.dialog_isok = false;
		}
		super.onResume();
	}

	private String getVersionName(){
		String versionName = "";
		try {
			versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
		} catch (PackageManager.NameNotFoundException e) {
			throw new RuntimeException(e);
		}
		return versionName;
	}

	/**
	 * 注册监听蓝牙OBD拔掉广播
	 */
	private void registerRecevie(){
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
		registerReceiver(mBluetoothReceiver, filter);
	}


	/**
	 * 初始化控件
	 */
	private void initViews(){
		FileReader.readConfig();
		//设置标题
		TextView title = (TextView) findViewById(R.id.tv_mainactivity_title);
		title.setText(getString(R.string.app_name) + " " + getString(R.string.Version));

		SharedPreferences settings = getSharedPreferences("Eol_KF", Context.MODE_PRIVATE);
		//3.生成一个保存编辑变量
		int  Communication= settings.getInt("Communication",0);
		Common.Communication=Communication;


		//3.生成一个保存编辑变量
		int printNum = settings.getInt("printNum",1);//默认打印机1
		Common.printNum=printNum;

		ArrayList<String> stations = cartype.getStationsList();
		ArrayList<String> names = new ArrayList<String>();
		mSize = stations.size();
		int [] iconId = new int[8];
		for(int i = 0; i < mSize; i++){
			if("返修".equals(stations.get(i))){
				iconId[i] = R.drawable.home_page_aftersale;
			}else{
				iconId[i] = R.drawable.home_page_diag;
			}
			names.add(stations.get(i));
		}
		//添加一个空白格
		//names.add("");
		//iconId[5] = R.drawable.home_page_blank;
		names.add(getString(R.string.Mainactivity_setting));
		iconId[6] = R.drawable.home_page_setting;

		names.add(getString(R.string.Mainactivity_problem));
		iconId[7] = R.drawable.home_page_problem;

		MainAdapter adapter = new MainAdapter(names, iconId, R.layout.activity_main_item);
		GridView gridview = (GridView) findViewById(R.id.gv_mainactivity);
		gridview.setAdapter(adapter);
		gridview.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
				showPage(pos);
			}
		});
	}

	/**
	 * 跳转功能界面
	 */
	private void showPage(int pos){
		if(pos < mSize)
		{//工位检测
			int settingPos = Integer.valueOf(Commonfunc.getSharedPreference(Common.STATION));
			if(settingPos == 0 || (settingPos - 1) == pos)//全部工位或者当前选择工位可做，其他工位不可做
			{
				cartype.clearCarInfo();
				Common.stationPos = pos;
				Common.stationName = cartype.getStationsList().get(pos);
				inputVin();
				//test();
			}else{
				CToast.show(R.string.Mainactivity_station_not_diagnose);
			}
		}
		else if(pos == (mSize + 0))
		{
			OnloginDialog();
		}else{//问题界面，当工位加返修大于等于5个就没有这个界面
			startActivity(new Intent(this,ProblemActivity.class));
		}
	}
	private void OnloginDialog()
	{
		final LoginDialog logDialog = new LoginDialog(this);
		logDialog.setOnOKButton(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String user = logDialog.GetNameString();
				String password = logDialog.GetPasswordString();
				if(user.equals("admin") && password.equals("kaifeng"))
				{
					logDialog.dismiss();
					startActivity(new Intent(MainActivity.this,SettingActivity.class));
				}
			}
		});
		logDialog.show();
		return;
	}
	void test()
	{
		//byte [] seed = {0x68, (byte) 0xC8,0x52, (byte) 0x7C};
		//byte [] key = new byte[4];
		//Security.Chery_AECS_Standard_SafeKey(seed,key);
		//key[0] += 0;
	}


	/**
	 * 输入VIN码
	 */
	private void inputVin(){
		final InputDialog inputDialog = new InputDialog(this);
		inputDialog.setTitle(R.string.Dialog_input_vin);
		//inputDialog.setEditString("LVTDB21B8RD201186");
		//inputDialog.setEditString("HJRPBGFB2RF082040");

		inputDialog.onClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String vin = inputDialog.getEditString();
				if(!Commonfunc.checkVinFormat(vin.getBytes())){
					CToast.show(R.string.Mainactivity_input_vin);
					inputDialog.setEditString("");
					return;
				}
//				if (vin.length()!=17){
//					CToast.show(R.string.Mainactivity_input_vin);
//					inputDialog.setEditString("");
//					return;
//				}
				cartype.vin = vin.getBytes();
				bluetooth.startRecord(new String(cartype.vin));
				bluetooth.PrintLog("Ver:" + getString(R.string.app_name) + "_" + getString(R.string.Version));
				bluetooth.PrintLog("Station:" + Common.stationName);
				bluetooth.PrintLog("Scan:" + new String(cartype.vin));
				if("1".equals(Commonfunc.getSharedPreference(Common.INTERNET,"0")))
				{
					inputDialog.dismiss();
					bluetooth.saveLogData(0, "获取地址:" + Common.mes_ver + "/Get_Electric");
					progressdialog = ProgressDialog.createDialog(context,"获取车辆配置信息...");
					new Thread(new Runnable() {
						@Override
						public void run()
						{
							// TODO Auto-generated method stub

							String tvin = new String(cartype.vin);
							String version = null;
							int isok = 0;

							for(int kk = 0; kk < 3; kk ++)
							{

								version = HttpRequest.sendRequestWithHttpURLConnection(tvin, Common.mes_ver + "/Get_Electric");
								/*version = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
										"<Parameters xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">\n" +
										"  <VinCode>HJRPBGFB2RF082040</VinCode>\n" +
										"  <MaterialCode>C6475LHBWJV0011</MaterialCode>\n" +
										"  <CarType>F01</CarType>\n" +
										"  <Soft_Code>6F7B60C191A45383</Soft_Code>\n" +
										"  <Status>OK</Status>\n" +
										"  <ECU name=\"EMS\">\n" +
										"    <Parameter name=\"Partnumber\">F18-3605010AM</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">F01R00D0RP</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\">F01RB0D0RP</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE1\">F05H0000C4</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\">A21107DK49</Parameter>\n" +
										"  </ECU>\n" +
										"  <ECU name=\"TCU\">\n" +
										"    <Parameter name=\"Partnumber\">F18-1500010GT</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.1</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">01.00.03</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\">01.00.04</Parameter>\n" +
										"  </ECU>\n" +
										"  <ECU name=\"BCM\">\n" +
										"    <Parameter name=\"Partnumber\">F01-3600030CE</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.4</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\">0.0.6</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE1\">00.02.04</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\">00.02.06</Parameter>\n" +
										"  </ECU>\n" +
										"  <ECU name=\"PEPS\">\n" +
										"    <Parameter name=\"Partnumber\">F01-3600210FA</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.1</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">00.01.01</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\" />\n" +
										"  </ECU>\n" +
										"  <ECU name=\"ESP\">\n" +
										"    <Parameter name=\"Partnumber\">F01-3570010FL</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.1</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">04.02.00</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\">05.02.00</Parameter>\n" +
										"  </ECU>\n" +
										"  <ECU name=\"ICM\">\n" +
										"    <Parameter name=\"Partnumber\">F01-3820010AJ</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.8</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">00.00.02</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\" />\n" +
										"  </ECU>\n" +
										"  <ECU name=\"EPS\">\n" +
										"    <Parameter name=\"Partnumber\">F08-3404010FD</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.1</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">00.00.01</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\">00.00.02</Parameter>\n" +
										"  </ECU>\n" +
										"  <ECU name=\"TBOX\">\n" +
										"    <Parameter name=\"Partnumber\">F01-7940015AD</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.1</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">00.00.10</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\">00.00.14</Parameter>\n" +
										"  </ECU>\n" +
										"  <ECU name=\"RADAR\">\n" +
										"    <Parameter name=\"Partnumber\">C11-7900303</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">0.0.1</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">00.01.01</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\" />\n" +
										"  </ECU>\n" +
										"  <ECU name=\"ABM\">\n" +
										"    <Parameter name=\"Partnumber\">F01-3658010NC</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">11</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">12</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\" />\n" +
										"  </ECU>\n" +
										"  <ECU name=\"RRM\">\n" +
										"    <Parameter name=\"Partnumber\">F01-7911020FC</Parameter>\n" +
										"    <Parameter name=\"HARDWARE1\">1.1.1</Parameter>\n" +
										"    <Parameter name=\"HARDWARE2\" />\n" +
										"    <Parameter name=\"SOFTWARE1\">00.09.01</Parameter>\n" +
										"    <Parameter name=\"SOFTWARE2\" />\n" +
										"  </ECU>\n" +
										"  <ECU name=\"TCU_FLASH\">\n" +
										"    <Parameter name=\"Code\">F18-1500010GT</Parameter>\n" +
										"    <Parameter name=\"DateName\">F18-1500010GT_01.00.02</Parameter>\n" +
										"  </ECU>\n" +
										"</Parameters>";*/
								if(version != null && version.length() > 10)
									break;
							}

							String v_msg = "OK";

							if(version == null || version.length() < 20)
							{
								//Toast.makeText(MainActivity.this, "联网获取信息失败!", Toast.LENGTH_LONG).show();
								v_msg = "联网获取信息失败!";
								bluetooth.saveLogData(0,v_msg);
								//测试方法2
								//String ver = HttpRequest.getcheryVersionFromMes(Common.mes_ver, "Get_Electric");
								isok = 0;

								//inputConfig();//输入配置码
							}
							else
								bluetooth.saveLogData(0,version);
							//progressdialog.setMessage("获取MES信息成功.");
							cartype.mesinfo = CommonXml.GetEcuInfoxml(version);
							String v_vin = cartype.mesinfo.getvin();
							//String v_tcucode = CommonXml.GetEcuFlashCode(cartype.mesinfo, "TCU_FLASH");
							cartype.tcufile = CommonXml.GetEcuFlashName(cartype.mesinfo, "TCU_FLASH");
							//v_tcuname += " ";
							//String soft = CommonXml.GetEcuInfoSoft(cartype.mesinfo, "CEM");
							//String hard = CommonXml.GetEcuInfoHard(cartype.mesinfo, "CEM");
							//String sn = CommonXml.GetEcuInfoSn(cartype.mesinfo, "CEM");

							if((v_vin != null) && v_vin.equals(tvin)) //获取到了
							{
								String config = cartype.mesinfo.getSoftCode();
								String car = cartype.mesinfo.getCarType();
								Section sec = FileReader.readSectionForIni(Common.GUEST + "car.ini", "CAR");
								if(sec != null)
								{
									String v_car = sec.get(car);
									if(v_car != null) //OK
									{
										//解析配置码
										cartype.config = config;
										byte [] byteConfig = new byte[config.length()/2];
										Commonfunc.hexStringToBytes(config, byteConfig);
										//特殊判断
										if(v_car.equals("KX63FL"))
										{
											if(((byteConfig[6] >> 4) & 0x0F) == 3) //2.0T
												v_car = "KX63FLB(2.0T)";
											else if(config.length() == 64) //就变成KX63A/B
												v_car = "KX63A";
										}
										else if(v_car.equals("KX63FLB")) //判断发动机类型来区分20211117  52+4
										{
											if(((byteConfig[6] >>> 4) & 0x0F) == 3) //2.0T
												v_car = "KX63FLB(2.0T)";
										}
										else if(v_car.equals("KQ53EV"))
										{
											if(((byteConfig[6] >>> 1) & 0x0F) == 3) //KQ51EV
												v_car = "KQ51EV";
										}
										else if(v_car.equals("KQ5"))
										{
											if(car.equals("H31") && v_vin.substring(0, 3).equals("HEV"))
												v_car = "KQ51EV";
										} else if (v_car.equals("T1PFL3")) {
											if(v_vin.substring(0,3).equals("HEV") || v_vin.substring(0,3).equals("LNN")){
												v_car = "T1PPHEV";
											}
										}
										else if (v_car.equals("CX62"))
										{
											if(cartype.config.length() == 167*2)
												v_car = "T1NFL1";
										}
										bluetooth.saveLogData(0,"Car:" + v_car);
										//刷写
										if (Common.stationPos == 3){   //需要通过EMS系统获取数据进行对应刷写的车

											bluetooth.saveLogData(0,"Station:" + Common.stationName);
											handler.obtainMessage(Common.DIALOG_SHOW_TEXT, 100, 0,"获取刷写信息...").sendToTarget();
											String ECUVersion=null;
											for(int kk = 0; kk < 3; kk ++)
											{
												ECUVersion = HttpRequest.sendGet(Common.mes_ems+tvin,"");
												//ECUVersion = "<ReturnList xmlns=\"http://schemas.datacontract.org/2004/07/ElecEquipmentHost.WCF\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Cartype/><Ecoscode1/><Ecoscode2/><Ecoscode3>*F01-3605010CH*8000C0008000FFFF/800200008017FFFF*F01R0AD5VL*/*</Ecoscode3><Materialcode>C6470L9BWFM0221</Materialcode><Status>success</Status><VinCode>LVTDB21B1SD601029</VinCode><XmlFile>.xml</XmlFile></ReturnList>";
												if(ECUVersion != null && ECUVersion.length() > 10) break;
											}
											bluetooth.mLog.PrintAppend("EMS:" +ECUVersion );
											cartype.ems = CommonXml.getEmsInfoxml(ECUVersion);
											bluetooth.saveLogData(0,"EMS:" + cartype.ems);
										}
										Commonfunc.setSharedPreference(Common.CAR, v_car);
										isok =1;
										cartype.car = v_car;
										bluetooth.mLog.PrintAppend("Car:" + v_car);
										//startDiagnose(cartype.car);
									}
									else
									{
										//Toast.makeText(MainActivity.this, "车型信息解析失败!", Toast.LENGTH_LONG).show();
										v_msg = "车型信息解析失败!";
										bluetooth.saveLogData(0,v_msg);

										isok =0;
										//inputConfig();//输入配置码
									}
								}
								else
								{
									//Toast.makeText(MainActivity.this, "车型配置获取失败!", Toast.LENGTH_LONG).show();
									v_msg = "车型配置获取失败!";
									bluetooth.saveLogData(0, v_msg);
									isok = 0;
									//inputConfig();//输入配置码
								}
							}
							else
							{
								//Toast.makeText(MainActivity.this, "MES数据解析失败或为空!", Toast.LENGTH_LONG).show();
								v_msg = "MES数据解析失败或为空!";
								bluetooth.saveLogData(0, v_msg);
								isok = 0;
							}

							handler.obtainMessage(Common.DIALOG_SHOW_PROGRESS, isok, 0,v_msg).sendToTarget();
						}
					}).start();

				}
				else
				{
					Toast.makeText(MainActivity.this, "手动模式!", Toast.LENGTH_SHORT).show();
					inputDialog.dismiss();
					inputConfig();//输入配置码
				}
			}

			/**
			 * 输入VIN码
			 */
			private void inputVin(){
				final InputDialog inputDialog = new InputDialog(MainActivity.this);
				inputDialog.setTitle(R.string.Dialog_input_vin);
				//inputDialog.setEditString("HJRPBGGB8NF116975");
				inputDialog.onClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						String vin = inputDialog.getEditString();
						if(!Commonfunc.checkVinFormat(vin.getBytes())){
							CToast.show(R.string.Mainactivity_input_vin);
							inputDialog.setEditString("");
							return;
						}
						cartype.vin = vin.getBytes();
						bluetooth.startRecord(new String(cartype.vin));
						bluetooth.PrintLog("Scan:" + new String(cartype.vin));

						if("1".equals(Commonfunc.getSharedPreference(Common.INTERNET,"0")))
						{
							inputDialog.dismiss();
							bluetooth.saveLogData(0, "获取地址:" + Common.mes_ver + "/Get_Electric");
							progressdialog = ProgressDialog.createDialog(context,"获取车辆配置信息...");
							new Thread(new Runnable() {
								@Override
								public void run()
								{
									// TODO Auto-generated method stub
									String tvin = new String(cartype.vin);
									String version = null;
									int isok = 0;
									for(int kk = 0; kk < 3; kk ++)
									{
										version = HttpRequest.sendRequestWithHttpURLConnection(tvin, Common.mes_ver + "/Get_Electric");
										if(version != null && version.length() > 10)
											break;
									}

									String v_msg = "OK";

									if(version == null || version.length() < 20)
									{
										//Toast.makeText(MainActivity.this, "联网获取信息失败!", Toast.LENGTH_LONG).show();
										v_msg = "联网获取信息失败!";
										bluetooth.saveLogData(0,v_msg);
										//测试方法2
										//String ver = HttpRequest.getcheryVersionFromMes(Common.mes_ver, "Get_Electric");
										isok = 0;

										//inputConfig();//输入配置码
									}
									else
									{
										//bluetooth.saveLogData(0, "Version:" + version);
									}
									cartype.mesinfo = CommonXml.GetEcuInfoxml(version);
									String v_vin = cartype.mesinfo.getvin();
									//String v_tcucode = CommonXml.GetEcuFlashCode(cartype.mesinfo, "TCU_FLASH");
									//String v_tcuname = CommonXml.GetEcuFlashName(cartype.mesinfo, "TCU_FLASH");
									//v_tcuname += " ";
									//String soft = CommonXml.GetEcuInfoSoft(cartype.mesinfo, "CEM");
									//String hard = CommonXml.GetEcuInfoHard(cartype.mesinfo, "CEM");
									//String sn = CommonXml.GetEcuInfoSn(cartype.mesinfo, "CEM");

									if((v_vin != null) && v_vin.equals(tvin)) //获取到了
									{
										String config = cartype.mesinfo.getSoftCode();
										String car = cartype.mesinfo.getCarType();
										Section sec = FileReader.readSectionForIni(Common.GUEST + "car.ini", "CAR");
										if(sec != null)
										{
											String v_car = sec.get(car);
											if(v_car != null) //OK
											{
												//解析配置码
												cartype.config = config;
												byte [] byteConfig = new byte[config.length()/2];
												Commonfunc.hexStringToBytes(config, byteConfig);
												//特殊判断
												if(v_car.equals("KX63FL"))
												{
													if(((byteConfig[6] >> 4) & 0x0F) == 3) //2.0T
														v_car = "KX63FLB(2.0T)";
													else if(config.length() == 64) //就变成KX63A/B
														v_car = "KX63A";
												}
												else if(v_car.equals("KX63FLB")) //判断发动机类型来区分20211117  52+4
												{

													if(((byteConfig[6] >>> 4) & 0x0F) == 3) //2.0T
														v_car = "KX63FLB(2.0T)";
												}
												else if(v_car.equals("KQ53EV"))
												{
													if(((byteConfig[6] >>> 1) & 0x0F) == 3) //KQ51EV
														v_car = "KQ51EV";
												}
												Commonfunc.setSharedPreference(Common.CAR, v_car);
												isok =1;
												cartype.car = v_car;
												//startDiagnose(cartype.car);
											}
											else
											{
												//Toast.makeText(MainActivity.this, "车型信息解析失败!", Toast.LENGTH_LONG).show();
												v_msg = "车型信息解析失败!";
												bluetooth.saveLogData(0,v_msg);

												isok =0;
												//inputConfig();//输入配置码
											}
										}
										else
										{
											//Toast.makeText(MainActivity.this, "车型配置获取失败!", Toast.LENGTH_LONG).show();
											v_msg = "车型配置获取失败!";
											bluetooth.saveLogData(0, v_msg);
											isok = 0;
											//inputConfig();//输入配置码
										}
									}
									else
									{
										//Toast.makeText(MainActivity.this, "MES数据解析失败或为空!", Toast.LENGTH_LONG).show();
										v_msg = "MES数据解析失败或为空!";
										bluetooth.saveLogData(0, v_msg);
										isok = 0;
									}

									handler.obtainMessage(Common.DIALOG_SHOW_PROGRESS, isok, 0,v_msg).sendToTarget();
								}
							}).start();

						}
						else
						{
							Toast.makeText(MainActivity.this, "手动模式!", Toast.LENGTH_SHORT).show();
							inputDialog.dismiss();
							inputConfig();//输入配置码
						}
					}
				});
			}
		});
	}

	/**
	 * 输入电池编码
	 */
	private void inputBattry(){
		final InputDialog dialog = new InputDialog(this);
		dialog.setTitle(R.string.Dialog_input_battary);
		dialog.onClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String battary = dialog.getEditString();
				int len = battary.length();
//				if(!(len == 16 || len == 64)){
//					dialog.setEditString("");
//					CToast.show(R.string.Mainactivity_input_config);
//					return;
//				}
				cartype.battary = battary;
				bluetooth.PrintLog("Scan:" + battary);
				dialog.dismiss();
				connectBluetooth();
			}
		});
	}

	/**
	 * 输入配置码
	 */
	private void inputConfig(){
		final InputDialog dialog = new InputDialog(this);
		dialog.setTitle(R.string.Dialog_input_config);
//		dialog.setEditString("6F89B1E0B0CD019506C85000040800AF087C011208100002881400000000000018048062181F00000000000000000000000000000000000000000000000000000000E4FDAB91302600363630000003800024E01C00100001000200010000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFF0200000000000000A0F8");
		//dialog.setEditString("FE0F001000000004");   //KQ53EV
		//dialog.setEditString("FE030A5000000400");   //KQ53A
		//dialog.setEditString("FE07145000020800");   //KQ55EV
//		dialog.setEditString("FE0F001000000604");   //KQ51EV
		//dialog.setEditString("0000000000000010");   //出口车
		//dialog.setEditString("040000000000000C");   //Q2020
		//dialog.setEditString("2542000103802A1C");    //KQ5
		//dialog.setEditString("6F1FC8E193A61F950040500001001803004A0080000080020000000000000000");//CX62B
		//dialog.setEditString("EF19B9B8F0CD47B136E27100E50C00AF0000013B901000028E0020000000000010F4B0CD4B9001000000000000000000000000000000000000000000000000000000A401BF92500D403436320200C520008420040010000100050081C1000000000000000000000000000004000000000000000002000000000000000000000000000000000000000000000000000000000000000000009F5A4FE58FF74700000000000000B01A");//T1PPHEV
//		dialog.setEditString("EF1FBFB9B1AD26B000427000630018E3006C040B300000050600000000000000080418400E9001000000000000000000000000000000000000000000000000000000AC01AE90100C103630020200430100040000001140010003004101000000000000000000000000000000000000000000000000000000000000000000");   //T1N
		//dialog.setEditString("6F5B78C9938A92040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010064017CF2104A271200000400032810000000001100000002000080104021000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009C6047854200CC200400000000006000");  //T1FL1
		dialog.onClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String config = dialog.getEditString();
//				int len = config.length();
//				if(!(len == 16 || len == 64)){
////					dialog.setEditString("");
////					CToast.show(R.string.Mainactivity_input_config);
////					return;
//				}
				cartype.config = config;
				bluetooth.PrintLog("Scan:" + config);
				selectCartype();
				dialog.dismiss();
			}
		});
	}

	/**
	 * 选择车型 如:A01
	 */
	public void selectCartype(){
		ArrayList<String> fileName = Commonfunc.getDirectorySonList(Common.GUEST);
		final SelectDialog dialog = new SelectDialog(this, fileName);
		dialog.setTitle(R.string.Dialog_select_cartype);
		String str_car = Commonfunc.getSharedPreference(Common.CAR);
		if(str_car != null)
			dialog.setDefault(str_car);
		dialog.onClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				String car = dialog.getContent();
				Commonfunc.setSharedPreference(Common.CAR, car);
				bluetooth.PrintLog("Select:" + car);
				startDiagnose(car);
			}
		});
	}

	/**
	 * 选择车型配置 如:尊贵型
	 */
	public void selectCartypeConfig(final String car){
		ArrayList<String> data = FileReader.readList(cartype.carDirectory + "cartype.ini", Common.MODE);
		final SelectDialog dialog = new SelectDialog(this,data);
		dialog.setTitle(R.string.Dialog_select_cartype_config);
		dialog.setDefault(Integer.valueOf(Commonfunc.getSharedPreference(Common.CARTYPE)));
		dialog.onClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				String cart = dialog.getContent();
				Commonfunc.setSharedPreference(Common.CARTYPE, dialog.getSelectItem() + "");
				startDiagnose(car, cart);
			}
		});
	}

	/**
	 * 开始诊断
	 * @param car 汽车车型 如A01
	 * @param cart 汽车配置 如尊贵型
	 */
	private void startDiagnose(String car, String... cart){
		if(cartype.initCartype(car, cart))
		{
			if(Common.Communication == 0) //使用蓝牙连接
			{
				bluetooth.PrintLog("Use bluetooth,connect to box.");
				connectBluetooth();
			}
			else					//使用有线连接
			{
				bluetooth.PrintLog("Use cable");
				startActivity(new Intent(this,DiagnoseActivity.class));
			}
//			if(Common.stationPos == 3)
//			{
//				startActivity(new Intent(this,DiagnoseActivity.class));
//			}
//			else{
////				if(Common.stationPos==2&&(cartype.car.equals("T1NPHEV")||cartype.car.equals("T1PPHEV")||cartype.car.equals("T1PFL3")))
////				{
////					inputBattry();
////				}else
//					connectBluetooth();
//			}
		}
		else
		{
			String v_show = "车型:" + car + "-->" + getString(R.string.Mainactivity_config_len_error);
			CToast.show(v_show);
		};
	}

	/**
	 * 连接蓝牙,进入诊断
	 */
	private void connectBluetooth(){
		if(mBlueService.isConnected())
		//if(true)
		{
			startActivity(new Intent(this,DiagnoseActivity.class));
		}else{//获取存入偏好设置的物理地址，自动连接
			mBlueService.setHandler(handler);
			mBlueService.setContext(this);
			mBlueService.connectDevice(Commonfunc.getSharedPreference(Common.MAC_ADDRESS, "00:00:00:00:00:00"));
			progressdialog = ProgressDialog.createDialog(this,"连接蓝牙...");
		}
	}

	/**
	 * 连接蓝牙后，自动返回进入诊断界面
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == Common.RESULT_OK){
			startActivity(new Intent(this, DiagnoseActivity.class));
		}
	}

	@Override //双击退出程序
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			long currentTime = System.currentTimeMillis();
			if(currentTime - historyTime < 1500){
				System.exit(0);
			}else{
				historyTime = currentTime;
				CToast.show(getString(R.string.Mainactivity_exit_app));
			}
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		this.unregisterReceiver(mBluetoothReceiver);
		super.onDestroy();
	}

	private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent){
			String action = intent.getAction();
			if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
				//在OBD拔掉之后大概10S才能接收到该广播
				BluetoothService.getInstance().stopService();
			}
		}
	};
}
